import 'dart:convert';
import 'dart:ui' as prefix0;

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../util/Toast.dart';
import '../../liz_mine/address/MyAddress.dart';
import '../../base/Constant.dart';
// import 'package:panda/base/SignType.dart';
import '../../entity/address_entity.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/AppSaveInfoUtil.dart';
import '../../util/LoadingUtil.dart';
import '../../util/SignUtil.dart';
import '../../liz_mine/order/OrderPay.dart';
import '../../liz_mine/set/Identity.dart';
import 'package:xlive_switch/xlive_switch.dart';
import '../goods/chooseCoupon.dart';

class PointBuyGoodsPage extends StatefulWidget {
  String goods_name = "";
  String goods_id = "";
  String goods_img = "";
  String price = "";
  String old = "";
  String skuJson = "";
  String skuInfo = "";
  String goods_num;
  String type = "0";
  String id = "0";
  String postage = '0';

  PointBuyGoodsPage(
      {Key key,
      @required this.goods_id,
      @required this.goods_name,
      @required this.goods_img,
      @required this.price,
      @required this.old,
      @required this.skuJson,
      @required this.goods_num,
      this.type,
      this.id,
      this.postage,
      @required this.skuInfo})
      : super(key: key);

  _PointBuyGoodsPageState createState() => _PointBuyGoodsPageState();
}

class _PointBuyGoodsPageState extends State<PointBuyGoodsPage>
    with WidgetsBindingObserver {
  var selectAddress = "";
  String detailAddress = "";
  var selectId = "";
  var selectNameAndPhone = "";
  int num_buy = 1;
  String token = "";
  // Map userMap = null;
  String truename = '';
  String id_num = '';
  bool check = true;
  bool isID = false;
  // String coupon_record_id;
  // String coupon_name = '选择优惠券';
  //  String coupon_money = '0';
  double money = 0;
  //   String receipt_name = '选择发票';
  //   String invoice_id;
  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return Container(
      child: new Scaffold(
          appBar: AppBar(
            title: Text('填写订单', style: TextStyle(fontSize: 18, color: black)),
            backgroundColor: white,
            brightness: Brightness.light,
            iconTheme: IconThemeData(color: black_99),
            elevation: 1.0,
          ),
          body: Stack(
            children: <Widget>[
              SingleChildScrollView(
                child: new Container(
                  color: divideColor,
                  height: MediaQuery.of(context).size.height -
                      kToolbarHeight -
                      MediaQueryData.fromWindow(prefix0.window).padding.top +
                      3 * kMargin140,
                  child: new Column(
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.all(kMargin15),
                        padding: EdgeInsets.all(15),
                        color: white,
                        child: new Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            selectAddress == ""
                                ? Container()
                                : Image.asset('images/order_adress_pre.png'),
                            Expanded(
                              child: GestureDetector(
                                onTap: () {
                                  Navigator.of(context)
                                      .push<AddressListDataData>(
                                          MaterialPageRoute(builder: (context) {
                                    return MyAddressPage(
                                      type: 1,
                                    );
                                  })).then((AddressListDataData data) {
                                    print(data);
                                    setState(() {
                                      selectAddress = data.province +
                                          data.city +
                                          data.county;
                                      detailAddress = data.detail_address;
                                      selectId = data.id;
                                      selectNameAndPhone = data.consignee +
                                          "  " +
                                          data.contact_number;
                                    });
                                  });
                                },
                                child: selectAddress == ""
                                    ? Padding(
                                        padding:
                                            EdgeInsets.fromLTRB(10, 0, 10, 0),
                                        child: Column(
                                          children: <Widget>[
                                            Image.asset(
                                                'images/order_adress_nor.png'),
                                            Container(
                                              height: kMargin30,
                                            ),
                                            Text('请选择收货地址',
                                                style: TextStyle(
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(
                                                            NORMAL_FONT_SIZE),
                                                    color: Colors.black45))
                                          ],
                                        ))
                                    : Padding(
                                        padding:
                                            EdgeInsets.fromLTRB(10, 0, 10, 0),
                                        child: new Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: <Widget>[
                                            Text(selectAddress,
                                                style: TextStyle(
                                                    color: black,
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(
                                                            SMALL_FONT_SIZE))),
                                            Text(detailAddress,
                                                style: TextStyle(
                                                    color: black,
                                                    fontSize:
                                                        ScreenUtil.getInstance()
                                                            .setSp(40),
                                                    fontWeight:
                                                        FontWeight.w500)),
                                            Padding(
                                              padding: EdgeInsets.fromLTRB(
                                                  0, 8, 0, 0),
                                              child: Text(selectNameAndPhone,
                                                  style: TextStyle(
                                                    color: black_99,
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(SMALL_FONT_SIZE),
                                                  )),
                                            ),
                                            Padding(
                                                padding: EdgeInsets.fromLTRB(
                                                    0, 8, 0, 0),
                                                child: Text('(收货不便时，请选择自提服务)',
                                                    style: TextStyle(
                                                        color: Colors.red,
                                                        fontSize: ScreenUtil
                                                                .getInstance()
                                                            .setSp(
                                                                SMALL_FONT_SIZE)))),
                                          ],
                                        ),
                                      ),
                              ),
                            ),
                            GestureDetector(
                              onTap: () {
                                Navigator.of(context).push<AddressListDataData>(
                                    MaterialPageRoute(builder: (context) {
                                  return MyAddressPage(
                                    type: 1,
                                  );
                                })).then((AddressListDataData data) {
                                  print(data);
                                  setState(() {
                                    selectAddress = data.province +
                                        data.city +
                                        data.county +
                                        data.detail_address;
                                    selectId = data.id;
                                    selectNameAndPhone = data.consignee +
                                        "  " +
                                        data.contact_number;
                                  });
                                });
                              },
                              child: Container(
                                color: white,
                                child: Icon(
                                  Icons.arrow_forward_ios,
                                  color: Colors.grey,
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                      Container(
                          margin: EdgeInsets.all(kMargin15),
                          color: white,
                          padding: EdgeInsets.all(15),
                          child: Column(
                            children: <Widget>[
                              new Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  widget.goods_img == ""
                                      ? Image.asset(
                                          'images/pic_default.png',
                                          width: ScreenUtil.getInstance()
                                              .setHeight(DP_120),
                                          height: ScreenUtil.getInstance()
                                              .setHeight(DP_120),
                                          fit: BoxFit.fill,
                                        )
                                      : Image.network(
                                          Api.ImgBaseUrl + widget.goods_img,
                                          width: ScreenUtil.getInstance()
                                              .setHeight(DP_120),
                                          height: ScreenUtil.getInstance()
                                              .setHeight(DP_120),
                                          fit: BoxFit.fill,
                                        ),
                                  Expanded(
                                    flex: 1,
                                    child: Container(
                                      padding: EdgeInsets.fromLTRB(10, 0, 5, 5),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: <Widget>[
                                          Text(
                                            widget.goods_name,
                                            maxLines: 2,
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(
                                                            NORMAL_FONT_SIZE),
                                                color: black,
                                                fontWeight: FontWeight.w500),
                                          ),
                                          Padding(
                                            padding:
                                                EdgeInsets.fromLTRB(0, 5, 5, 0),
                                            child: Text(
                                              widget.skuInfo,
                                              style: TextStyle(
                                                  fontSize:
                                                      ScreenUtil.getInstance()
                                                          .setSp(
                                                              MINI_FONT_SIZE),
                                                  color: black_99),
                                            ),
                                          ),
                                          Text(
                                            widget.price + '积分',
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(34),
                                                color: mainColor),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              Container(
                                color: white,
                                padding: EdgeInsets.fromLTRB(15, 0, 10, 10),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: Text('购买数量',
                                          style: TextStyle(
                                              color: black, fontSize: 14)),
                                    ),
                                    Row(
                                      children: <Widget>[
                                        new GestureDetector(
                                          onTap: () {
                                            if (num_buy <= 1) {
                                              return;
                                            }
                                            num_buy--;
                                            setState(() {});
                                          },
                                          child: Icon(
                                            Icons.remove,
                                            color: black,
                                            size: ScreenUtil.getInstance()
                                                .setHeight(DP_30),
                                          ),
                                        ),
                                        Text('  '),
                                        Text(
                                          num_buy.toString(),
                                          style: TextStyle(
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(33),
                                              color: black_99),
                                        ),
                                        Text('  '),
                                        new GestureDetector(
                                          onTap: () {
                                            num_buy++;
                                            setState(() {});
                                          },
                                          child: Icon(
                                            Icons.add,
                                            size: ScreenUtil.getInstance()
                                                .setHeight(DP_30),
                                            color: black,
                                          ),
                                        )
                                      ],
                                    )
                                  ],
                                ),
                              ),
                            ],
                          )),
                      Container(
                        margin: EdgeInsets.all(kMargin15),
                        padding: EdgeInsets.fromLTRB(10, 8, 10, 0),
                        color: white,
                        child: Column(
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Text(
                                  '支付人',
                                  style: TextStyle(
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(SMALL_FONT_SIZE)),
                                ),
                                Container(
                                  width: kMargin10,
                                  height: 1,
                                ),
                                Expanded(
                                  flex: 1,
                                  child: Text(
                                    truename + ' ' + id_num,
                                    style: TextStyle(
                                        color: black,
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(SMALL_FONT_SIZE)),
                                  ),
                                ),
                                GestureDetector(
                                    onTap: () {
                                      Navigator.of(context).push(
                                          MaterialPageRoute(builder: (context) {
                                        return new IdentityPage();
                                      }));
                                    },
                                    child: Text(
                                      '更换',
                                      style: TextStyle(
                                          color: Colors.blue,
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(SMALL_FONT_SIZE)),
                                    ))
                              ],
                            ),
                            Container(
                              width: ScreenUtil.getInstance().setWidth(750),
                              height: kMargin15,
                            ),
                            Row(
                              children: <Widget>[
                                Image.asset('images/order_pay.png'),
                                Container(
                                  width: kMargin15,
                                  height: 1,
                                ),
                                Expanded(
                                  child: Text(
                                    '海关规定购买跨境商品，须验证实际支付人身份信息，否则导致无法清关',
                                    style: TextStyle(
                                        color: Colors.grey,
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE)),
                                  ),
                                )
                              ],
                            ),
                            Container(
                              width: ScreenUtil.getInstance().setWidth(750),
                              height: kMargin15,
                            ),
                          ],
                        ),
                      ),
                      Container(
                          margin: EdgeInsets.all(kMargin15),
                          color: white,
                          padding: EdgeInsets.fromLTRB(10, 8, 10, 0),
                          child: Column(
                            children: <Widget>[
                              Container(
                                width: ScreenUtil.getInstance().setWidth(750),
                                height: kMargin15,
                              ),
                              Row(
                                children: <Widget>[
                                  Expanded(
                                    child: Text('商品总额',
                                        style: TextStyle(
                                            color: black,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(NORMAL_FONT_SIZE))),
                                  ),
                                  Text(
                                    (money * num_buy).toString() + '积分',
                                    style: TextStyle(
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE),
                                      color: black,
                                    ),
                                  ),
                                ],
                              ),
                              Container(
                                width: ScreenUtil.getInstance().setWidth(750),
                                height: kMargin40,
                              ),
                              // Row(
                              //   children: <Widget>[
                              //     Expanded(
                              //       child: Text('运费',
                              //           style: TextStyle(
                              //               color: black,
                              //               fontSize: ScreenUtil.getInstance()
                              //                   .setSp(NORMAL_FONT_SIZE))),
                              //     ),
                              //     Text(
                              //       '¥' + widget.postage,
                              //       style: TextStyle(
                              //         fontSize: ScreenUtil.getInstance()
                              //             .setSp(NORMAL_FONT_SIZE),
                              //         color: black,
                              //       ),
                              //     ),
                              //   ],
                              // ),
                              // Container(
                              //   width: ScreenUtil.getInstance().setWidth(750),
                              //   height: kMargin40,
                              // ),
                              // Row(
                              //   children: <Widget>[
                              //     Expanded(
                              //       child: Text('税费',
                              //           style: TextStyle(
                              //               color: black,
                              //               fontSize: ScreenUtil.getInstance()
                              //                   .setSp(NORMAL_FONT_SIZE))),
                              //     ),
                              //     Text(
                              //       '¥0.00',
                              //       style: TextStyle(
                              //         fontSize: ScreenUtil.getInstance()
                              //             .setSp(NORMAL_FONT_SIZE),
                              //         color: black,
                              //       ),
                              //     ),
                              //   ],
                              // ),
                              Container(
                                width: ScreenUtil.getInstance().setWidth(750),
                                height: kMargin30,
                              ),
                            ],
                          )),
                      Container(
                        margin: EdgeInsets.all(kMargin15),
                        color: white,
                        padding: EdgeInsets.fromLTRB(10, 8, 10, 10),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text('本人已知悉并同意',
                                  style: TextStyle(
                                      color: black,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE))),
                            ),
                            Expanded(
                              child: GestureDetector(
                                onTap: () {},
                                child: Text('用户协议',
                                    style: TextStyle(
                                        color: Colors.green,
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE))),
                              ),
                            ),
                            XlivSwitch(
                              value: this.check,
                              activeColor: mainColor, // 激活时原点颜色
                              unActiveColor: Colors.grey,
                              onChanged: (bool val) {
                                checkInform();
                              },
                            )
                          ],
                        ),
                      ),
                      Expanded(
                        child: Container(
                          color: divideColor,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(
                    top: MediaQuery.of(context).size.height -
                        kToolbarHeight -
                        MediaQueryData.fromWindow(prefix0.window).padding.top -
                        kBottomNavigationBarHeight),
                color: white,
                padding: EdgeInsets.all(10),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: Text(
                        (money * num_buy).toString() + '积分',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance().setSp(40),
                            color: mainColor),
                      ),
                    ),
                    new Container(
                      height: 35,
                      decoration: new BoxDecoration(
                          color: mainColor,
                          borderRadius: BorderRadius.circular(40.0)),
                      child: new FlatButton(
                        child: new Padding(
                          padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                          child: new Text(
                            "提交订单",
                            style: new TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil.getInstance().setSp(30)),
                          ),
                        ),
                        onPressed: () {
                          if (isID == false) {
                            // Fluttertoast.showToast(msg: '请进行实名认证');
                            Toast.toast(context, msg: '请进行实名认证');
                            return;
                          }
                          if (selectId == "") {
                            // Fluttertoast.showToast(msg: "请选择收货地址");
                            Toast.toast(context, msg: '请选择收货地址');
                            return;
                          }

                          showDialog(
                              context: context,
                              barrierDismissible: false,
                              builder: (_) {
                                return new NetLoadingDialog(
                                  dismissCallback: _disMissCallBack,
                                  loadingText: "下单中...",
                                  bgColor: Color.fromARGB(255, 0, 0, 0),
                                  requestCallBack: null,
                                  outsideDismiss: false,
                                );
                              });

                          buy();
                        },
                      ),
                    )
                  ],
                ),
              )
            ],
          )),
    );
  }

  _disMissCallBack(Function func) {
    func();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    money = double.parse(widget.price);
    num_buy = int.parse(widget.goods_num);
    getString(TOKEN).then((value) {
      token = value;
      getAUTHRESULT();
      loadList();
    });
  }

  loadList() async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_ADDRESS_LIST),
      "token": token,
      "p": 1,
      "per": "100"
    });
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_ADDRESS_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] != 1) {
      // Fluttertoast.showToast(msg: userMap['msg']);
      Toast.toast(context, msg: userMap['msg']);
      return;
    }
    AddressListEntity homeListEntity = new AddressListEntity.fromJson(userMap);
    if (mounted)
      for (int i = 0; i < homeListEntity.data.datas.length; i++) {
        if ("Y" == homeListEntity.data.datas[i].is_default) {
          selectAddress = homeListEntity.data.datas[i].province +
              homeListEntity.data.datas[i].city +
              homeListEntity.data.datas[i].county;
          detailAddress = homeListEntity.data.datas[i].detail_address;
          selectId = homeListEntity.data.datas[i].id;
          selectNameAndPhone = homeListEntity.data.datas[i].consignee +
              "  " +
              homeListEntity.data.datas[i].contact_number;
          // selectName = homeListEntity.data.datas[i].consignee.toString();
          break;
        }
      }

    setState(() {});
  }

  checkInform() async {
    if (check == true) {
      setState(() {
        check = false;
        // saveBoolean(INFORM, check);
      });
      return;
    } else {
      if (check == false) {
        setState(() {
          check = true;
          // saveBoolean(INFORM, check);
        });
        return;
      }
    }
  }

  getAUTHRESULT() async {
    //获取实名认证信息
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_USER_AUTHRESULT),
      'token': token,
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_USER_AUTHRESULT, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap['code'];

    if (code == 1) {
      if (userMap['data']['authMsg'] is List &&
          userMap['data']['authMsg'].length == 0) {
        setState(() {
          isID = false;
        });
        // Fluttertoast.showToast(msg: '实名信息未通过审核或未提交审核');
        showDialog(
          context: context,
          builder: (context) => new AlertDialog(
            title: new Text('提示'),
            content: new Text('实名信息未通过审核或未提交审核'),
            actions: <Widget>[
              new FlatButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: new Text(
                  '知道了',
                  style: TextStyle(color: Colors.grey),
                ),
              ),
              new FlatButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: new Text(
                  '联系客服',
                  style: TextStyle(color: Colors.grey),
                ),
              ),
              new FlatButton(
                onPressed: () {
                  Navigator.of(context)
                      .push(MaterialPageRoute(builder: (context) {
                    return new IdentityPage();
                  }));
                },
                child: new Text('实名认证', style: TextStyle(color: mainColor)),
              ),
            ],
          ),
        );
      } else {
        print('===实名认证000===');
        print(userMap);

        setState(() {
          isID = true;
          truename = userMap['data']['authMsg']['truename'];
          id_num = userMap['data']['authMsg']['id_num'];
        });
      }
    }
  }

  buy() async {
     Map map = new Map.from({
      'token': token,
    });
    map['goods_id'] = widget.goods_id;
    map['goods_sku'] = widget.skuJson.toString().replaceAll(" ", "");
    map['num'] = num_buy;
    map['address_id'] = selectId;
        print(map);

    Response<String> response =
        await HttpUtil().post(Api.URL_POINTORDER_BUY, data: map);
    Map userMap = json.decode(response.data);
    int code = userMap['code'];
    Navigator.of(context).pop(1);
    print(userMap);
    if (code == 1) {
      // Fluttertoast.showToast(msg: '下单成功');
      Toast.toast(context, msg: '下单成功');
      Navigator.of(context).pop();
    } else {
      // Fluttertoast.showToast(msg: userMap['msg']);
      Toast.toast(context, msg: userMap['msg']);
      userMap = null;
    }
    return;
  }
}
